package cn.wolfcode.mq;

import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
        consumerGroup = "MQCreateOrderListener",
        topic = MQConstant.ORDER_PEDDING_TOPIC
)
@Slf4j
public class MQCreateOrderListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage orderMessage) {
        log.info("进入到创建订单的消费者中");
        Long seckillId = orderMessage.getSeckillId();
        Integer time = orderMessage.getTime();
        String token = orderMessage.getToken();
        Long userPhone = orderMessage.getUserPhone();

        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setToken(token);
        orderMQResult.setSeckillId(seckillId);
        orderMQResult.setTime(time);
        //定义一个标签
        String tag = "";
        try {
//            int i = 1/0;
            //执行秒杀业务逻辑
            String orderNo = orderInfoService.doSeckill(seckillId, time, userPhone);
            //token     seckillId   time    orderNo
            orderMQResult.setOrderNo(orderNo);
            tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;
            //发送一个延迟消息
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC,
                    MessageBuilder.withPayload(orderMQResult).build(),5000,15);
        } catch (Exception e) {
            e.printStackTrace();
            //seckillId     time    token   code    msg
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            tag = MQConstant.ORDER_RESULT_FAIL_TAG;
        }
        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC+":"+tag,orderMQResult);
    }
}
